#include "Game.h"
#include "ReportError.h"

Game::Game()
{
	m_pCurrentState = 0;
}

Game::~Game()
{

}

void Game::SetGameState(const char* StateName)
{
	GameState* OldGameState = m_pCurrentState;

	//check if not 0 so you dont activate state again
	if (OldGameState != 0)
	{
		m_pCurrentState->OnDeActive();
	}

	m_pCurrentState = m_States[StateName];

	//if changing states
	if (OldGameState != m_pCurrentState)
	{
		m_pCurrentState->OnActive();
	}
}

void Game::SetGameState(const GameState* State)
{
	GameState* OldGameState = m_pCurrentState;

	//check if not 0 so you dont activate state again
	if (OldGameState != 0)
	{
		m_pCurrentState->OnDeActive();
	}

	m_pCurrentState = m_States[State->NAME];

	//if changing states
	if (OldGameState != m_pCurrentState)
	{
		m_pCurrentState->OnActive();
	}
}

bool Game::AddGameState(const std::string& StateName, GameState* gs)
{
	//add the state if cannot find the state in the map
	States::iterator It = m_States.find(StateName);
	if(It == m_States.end())
	{
		m_States[StateName] = gs;
		return true;
	}

	else
	{
		std::string Error = "GameState Already Exists: " + It->first;
		ReportError(Error);
		return false;
	}
}

void Game::Run()
{
	Update();
	Draw();
}

bool Game::Load()
{
	for (States::iterator It = m_States.begin();
		It != m_States.end();
		++It)
	{
		GameState* Gd = It->second;
		if (!Gd->Load())
		{
			std::string Error = "Failed to load a game state! " + It->first;
			ReportError(Error);
			return false;
		}
	}
	return true;
}

void Game::Update()
{
	m_pCurrentState->Update();
}

void Game::Draw()
{
	m_pCurrentState->Draw();
}
